package com.example.springsecurity.util;

import io.jsonwebtoken.Claims;
import io.jsonwebtoken.JwtBuilder;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import org.apache.commons.lang3.time.DateUtils;
import org.springframework.stereotype.Component;

import java.util.Date;
import java.util.Map;

/**
 * @author wuancheng
 * @date 2024/6/21 9:57
 * @description jwt工具类
 */
public class JwtUtil {

    public final static String JWT_KEY = "cKWGPTjjcNdLXw3Ul5LGAryfNWaxlVAQH0ZExKaZeI4=";

    public final static Integer JWT_TTL = 3600;

    /**
     * 创建一个token
     *
     * @param id 用户唯一ID
     * @return
     */
    public static String[] createJwt(String id) {
        return createJwt(id, null, null);
    }

    private static String[] createJwt(String id, String subject, Map<String, Object> claims) {
        Date now = new Date();
        JwtBuilder builder = Jwts.builder().setId(id).setSubject(subject).setIssuedAt(now).signWith(SignatureAlgorithm.HS256, JWT_KEY);
        if (claims != null && !claims.isEmpty()) {
            builder.addClaims(claims);
        }

        Date expire = null;
        if (JWT_TTL > 0) {
            expire = DateUtils.addSeconds(now, JWT_TTL);
            builder.setExpiration(expire);
        }

        String jwt = builder.compact();
        return new String[]{jwt, null != expire ? String.valueOf(expire.getTime()) : ""};
    }

    public static Claims parseJwt(String jwtToken) throws Exception {
        Claims claims = Jwts.parser().setSigningKey(JWT_KEY).parseClaimsJws(jwtToken).getBody();
        return claims;
    }

    /**
     * 解析token并获取存如的id
     *
     * @param jwtToken
     * @return
     * @throws Exception
     */
    public static String parseJwtGetId(String jwtToken) throws Exception {
        Claims claims = parseJwt(jwtToken);
        return claims.getId();
    }
}

